package org.example.producer;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.errors.ProducerFencedException;
import org.apache.kafka.common.serialization.StringSerializer;

import java.util.Properties;

/**
 * 自定义生产者
 */
public class CustomProducerTransaction {
    public static void main(String[] args) {
        Properties properties = new Properties();
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "10.211.55.104:9092");

        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        //properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");

        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);

        // 事务id
        properties.put(ProducerConfig.TRANSACTIONAL_ID_CONFIG,"transaction-id-01");

        try (KafkaProducer<String, String> kafkaProducer = new KafkaProducer<String, String>(properties)) {

            kafkaProducer.initTransactions();
            kafkaProducer.beginTransaction();
            try {
                for (int i = 0; i < 5; i++) {
                    kafkaProducer.send(new ProducerRecord<>("first", "fengliulin - " + i));
                }
                int i = 1/0;
                kafkaProducer.commitTransaction();
            } catch (Exception e) {
                kafkaProducer.abortTransaction();
            }
        }
    }
}

